package com.luyuan.framework.security.authentication;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 微信小程序用户认证提供者
 * 微信小程序用户通过openid进行认证，不需要密码
 * 
 * @author luyuan
 */
public class WxappAuthenticationProvider implements AuthenticationProvider {
    
    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String openid = (String) authentication.getPrincipal();
        
        if (openid == null || openid.isEmpty()) {
            throw new BadCredentialsException("无效的openid");
        }
        
        UserDetails userDetails = userDetailsService.loadUserByUsername(openid);
        
        // 微信小程序用户不需要验证密码
        return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}